import { createContext, useState, useEffect, useCallback, useMemo} from "react"
import { useContext } from "react"

// const UserContext=createContext()  
const UserContextUpdater=createContext()//写 state
const UserContextState=createContext()//读取state

const useUserContextState=()=>{
    const context=useContext(UserContextState)
    if(context===undefined){
        throw new Error(
            'useUserContextState必须卸载自己的Provider的使用'
        )
    }
    return context
}

const useUserContextUpdater=()=>{
    const context=useContext(UserContextUpdater)
    if(context===undefined){
        throw new Error(
            'useUserContextUpdater必须卸载自己的Provider的使用'
        )
    }
    return context
}



const UserContextProvider=({children})=>{ 
    const [user,setUser]=useState(null)

const signout=useCallback(()=>{
    setUser(null)
},[])

    useEffect(()=>{
        const controller=new AbortController()
        // controller.abort
        fetch('https://randomuser.me/api',{signal:controller.signal}).then(resp=>resp.json())
        .then(json=>new Promise(resolve=>setTimeout(()=>resolve(json),3000)))
        .then(json=>setUser(json.results[0]))
        .catch(error=>console.log('错误',error))
        return()=>{
        controller.abort()
    }
    },[])
//   const contextValue=useMemo(()=>({user,signout}),[user,signout])
    return(
     <UserContextState.Provider value={user}>
     <UserContextUpdater.Provider value={signout}>
           {children}
     </UserContextUpdater.Provider>
     </UserContextState.Provider>
    )
}
// const useUserContext=()=>{
//     const context=useContext(UserContext)
//     if(context===undefined){
//         throw new Error('userContext必须在<UserContextProvider>内部使用')
//     }
//     return context
// }
export {UserContextProvider, useUserContextState, useUserContextUpdater}